/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// win_console.cpp - cool windows console


#include "..\global.h"
#include "win_console.h"

#include <crtdbg.h>


/*-----------------------------------------------------------------------------
	EXPORT STUFF
-----------------------------------------------------------------------------*/
DLL_EXPORT	IConsole	*CreateConsole(void)
{
	return new EWinConsole();
}


DLL_EXPORT	void	DestroyConsole(IConsole *con)
{
	delete con;
}


/*-----------------------------------------------------------------------------
	style, color font etc.
-----------------------------------------------------------------------------*/

#define WS_WINDOW		WS_CLIPCHILDREN | WS_CLIPSIBLINGS
#define WBORDER			2*GetSystemMetrics(SM_CXFIXEDFRAME)
#define HBORDER			2*GetSystemMetrics(SM_CYFIXEDFRAME)+GetSystemMetrics(SM_CYCAPTION)

#define USE_DEBUG_WINDOW	1

#define CONSOLE_CLASSNAME	"Console Window"
#define CONSOLE_WNDNAME		"Console"

#define SYSCON_TEXTCOLOR	0xFFFFFF	//	New Theme
#define SYSCON_BACKGROUND	0x202020
#define SYSCON_WINDOWCOLOR	0x404040	//*/
														
/*#define SYSCON_FONT			"Lucida Console"
#define SYSCON_FONTWIDTH	0
#define SYSCON_FONTHEIGHT	18*/
#define SYSCON_FONT			"Courier"
#define SYSCON_FONTWIDTH	0
#define SYSCON_FONTHEIGHT	12	//*/
/*#define SYSCON_FONT			"Terminal"
#define SYSCON_FONTWIDTH	8
#define SYSCON_FONTHEIGHT	-12*/


#define	SYSCON_WIDTH		800
#define SYSCON_HEIGHT		500
#define SYSCON_LINEHEIGHT	15
#define SYSCON_SPLIT		1

#define	SYSCON_POS_X		20
#define SYSCON_POS_Y		20


/*-----------------------------------------------------------------------------
	Constructor/Destructor
-----------------------------------------------------------------------------*/

EWinConsole::EWinConsole(void)
{		  
	scroll = 0;

	CreateConsoleWindow();
}


EWinConsole::~EWinConsole(void)
{
	DestroyConsoleWindow();
}


/*-----------------------------------------------------------------------------
	Command Line Editor
-----------------------------------------------------------------------------*/
EEditCmdLine::EEditCmdLine(void) 
{
	Clear();
}

EEditCmdLine::~EEditCmdLine(void) 
{
}

void EEditCmdLine::SetString(const char *str)
{
	cmdline = str;
	cursor  = cmdline.length();
}

void EEditCmdLine::Clear(void)
{	
	SetString("");
}

void EEditCmdLine::InsertChar(char ch)
{
	cmdline.insert( cmdline.begin()+cursor, ch);
	Right();
}

void EEditCmdLine::Backspace(void)
{
	if ( cursor>=1 ) {
		cmdline.erase( cmdline.begin()+cursor-1 );
		Left();
	}
}

void EEditCmdLine::Delete(void)
{
	if ( cursor < cmdline.length() ) {
		cmdline.erase( cmdline.begin()+cursor );
	}
}

void EEditCmdLine::Left(void)
{
	cursor--;
	if (cursor<0) cursor = 0;
	if (cursor>cmdline.length()) cursor = cmdline.length();
}

void EEditCmdLine::Right(void)
{
	cursor++;
	if (cursor<0) cursor = 0;
	if (cursor>cmdline.length()) cursor = cmdline.length();
}


/*-----------------------------------------------------------------------------
	Stuff
-----------------------------------------------------------------------------*/

//
//	XTSystem::WriteConsole
//
void EWinConsole::WriteLine(const char *text)
{
	WaitForSingleObject(con_mutex, INFINITE);
		lines.push_back(text);
		scroll = lines.size();
		UpdateConsole();
	ReleaseMutex(con_mutex);
}


void EWinConsole::SetCmdLine(const char *buffer)
{
	WaitForSingleObject(con_mutex, INFINITE);
		cmdline.SetString(buffer);
		UpdateConsole();
	ReleaseMutex(con_mutex);
}


bool EWinConsole::GetCmdLine(char *buffer, uint size)
{
	WaitForSingleObject(con_mutex, INFINITE);
	
		if (cmd_queue.empty()) {
			ReleaseMutex(con_mutex);
			return false;
		}
		
		strncpy(buffer, cmd_queue.front().c_str(), size);
		cmd_queue.pop();

	ReleaseMutex(con_mutex);
	return true;
}


/*//
//	EWinConsole::GetConsoleLine
//
const char *EWinConsole::GetLine(uint line)
{
	if (line>=lines.size()) {
		return NULL;
	}
	return lines[line].c_str();
}


uint EWinConsole::GetLineNum(void)
{
	return (uint)lines.size();
}
*/

/*-----------------------------------------------------------------------------
	Private stuff
-----------------------------------------------------------------------------*/

//
//	EWinConsole::CreateConsoleWindow
//
void EWinConsole::CreateConsoleWindow(void)
{
	VERIFY( AllocConsole() );
	
	//	Create console mutex :
	con_mutex = CreateMutex(0, FALSE, 0);
	ASSERT(con_mutex);
	
	//	Create console :
	hinput	= GetStdHandle (STD_INPUT_HANDLE);
	houtput	= GetStdHandle (STD_OUTPUT_HANDLE);
	
	SetConsoleTitle(CONSOLE_WNDNAME);
	
	CONSOLE_SCREEN_BUFFER_INFO	info;
	COORD						coordMax;
 
	coordMax = GetLargestConsoleWindowSize(houtput);
	VERIFY( GetConsoleScreenBufferInfo(houtput, &info) );
	
	//	Set console attributes :
	COORD size;
	size.X = SIZE_X;
	size.Y = SIZE_Y;	
	
	info.srWindow.Left	= 0;
	info.srWindow.Right	= SIZE_X - 1;
	info.srWindow.Top	= 0;
	info.srWindow.Bottom= SIZE_Y - 1;
	VERIFY( SetConsoleWindowInfo(houtput, TRUE, &info.srWindow) );
	SetConsoleScreenBufferSize(houtput, size);

	//	Set console font :
	//	TODO : This function is Windows Vista only.
	/*
	CONSOLE_FONT_INFOEX font;
	memset(&font, 0, sizeof(font));
	font.cbSize = sizeof(font);
	VERIFY( GetCurrentConsoleFontEx(houtput, FALSE, &font) );
	
	font.dwFontSize.X = 10;
	font.dwFontSize.Y = 18;
	VERIFY( SetCurrentConsoleFontEx(houtput, FALSE, &font) );
	*/

	//	Move console :	
	HWND hcon_wnd = GetConsoleWindow();

	RECT rect, desk_rect;
	GetWindowRect( hcon_wnd, &rect );
	GetWindowRect( GetDesktopWindow(), &desk_rect );
	  
	int w = 4999;//rect.right - rect.left;
	int h = 4999;//rect.bottom - rect.top;
	int x = 50;
	int y = 50;

	MoveWindow( hcon_wnd, x, y, w, h, TRUE );	

	//	Create console input thread :
	hcon_thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE )ConsoleThread, this, 0, NULL);
	ASSERT(hcon_thread);
}


//
//	EWinConsole::DestroyConsoleWindow()
//
void EWinConsole::DestroyConsoleWindow(void)
{
	VERIFY( CloseHandle( con_mutex ) );
	VERIFY( CloseHandle(hcon_thread) );
	FreeConsole();
}


//
//	EWinConsole::ConsoleThread
//
unsigned __stdcall EWinConsole::ConsoleThread( EWinConsole *self )
{
	DWORD num, a;
	
	INPUT_RECORD	input_rec;
	
	while (1) {
		
		ReadConsoleInput(self->hinput, &input_rec, 1, &num);

		WaitForSingleObject(self->con_mutex, INFINITE);
		
		bool pressed = false;
		
		if ( input_rec.EventType==WINDOW_BUFFER_SIZE_EVENT ) {
			self->UpdateConsole();
		}
		
		if ( input_rec.EventType==KEY_EVENT ) {
			if ( input_rec.Event.KeyEvent.bKeyDown ) {
				pressed = true;
			}
		}
		
		if ( pressed ) {
					 
			char ch   = input_rec.Event.KeyEvent.uChar.AsciiChar;
			uint scan = input_rec.Event.KeyEvent.wVirtualScanCode;
			uint key  = input_rec.Event.KeyEvent.wVirtualKeyCode;

			if (key==KEY_ENTER) {
				self->cmd_queue.push(self->cmdline.cmdline);
				self->cmdline.Clear();
			}		
			if (key==KEY_TAB) {
				self->cmd_queue.push("*complete");
				self->cmd_queue.push(self->cmdline.cmdline);
			}
			
			if (ch>=' ') {
				self->cmdline.InsertChar( ch );
			} else {
				if (key==KEY_UP)		self->cmd_queue.push("*prev");
				if (key==KEY_DOWN)		self->cmd_queue.push("*next");
				
				if (key==KEY_LEFT)		self->cmdline.Left();
				if (key==KEY_RIGHT)		self->cmdline.Right();
				if (key==KEY_BACKSPACE) self->cmdline.Backspace();
				if (key==KEY_DEL)		self->cmdline.Delete();

				//	Scrolling stuff :				
				if (key==KEY_PGUP) {	self->scroll -= 2;	}
				if (key==KEY_PGDN) {	self->scroll += 2;	}
				if (key==KEY_HOME) {	self->scroll =  0;	}
				if (key==KEY_END)  {	self->scroll =  self->lines.size();	}
				int min_scroll = min(1, self->lines.size());
				self->scroll = Clamp<int>(self->scroll, min_scroll, self->lines.size());
			}
			self->UpdateConsole();	
		}
		
		ReleaseMutex(self->con_mutex);
	}
	
	ExitThread(0);
	return 0;
}

/*-----------------------------------------------------------------------------
	Console redering stuff :
-----------------------------------------------------------------------------*/

static const uint CON_TEXT_COLORS[8]	=	{
		0,
		FOREGROUND_INTENSITY | FOREGROUND_BLUE,
		FOREGROUND_INTENSITY | FOREGROUND_GREEN,
		FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE,

		FOREGROUND_INTENSITY | FOREGROUND_RED,
		FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE,
		FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN,
		FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
	};


//
//	EWinConsole::
//
void EWinConsole::DrawChar(int x, int y, char ch)
{
	if (x<0 || x>=SIZE_X) return;
	if (y<0 || y>=SIZE_Y) return;
	buffer[x + y * SIZE_X].Attributes = current_color;
	buffer[x + y * SIZE_X].Char.AsciiChar = ch;
}


//
//	EWinConsole::
//
void EWinConsole::DrawString(int x, int y, const char *str)
{
	uint len = strlen(str);
	for (uint i=0; i<len; i++) {
		DrawChar(x + i, y, str[i]);
	}
}


//
//	EWinConsole::
//
void EWinConsole::DrawStringClr(int x, int y, const char *str)
{
	uint old_color = current_color;
	uint len = strlen(str);
	uint xoffs = 0;
	uint color = CON_TEXT_COLORS[7];
	
	for (uint i=0; i<len; i++) {
		byte ch = str[i];
		
		if (ch=='^') {
			i++;
			ch = str[i];
			
			if (ch=='0') color = CON_TEXT_COLORS[0];
			if (ch=='1') color = CON_TEXT_COLORS[1];
			if (ch=='2') color = CON_TEXT_COLORS[2];
			if (ch=='3') color = CON_TEXT_COLORS[3];
			if (ch=='4') color = CON_TEXT_COLORS[4];
			if (ch=='5') color = CON_TEXT_COLORS[5];
			if (ch=='6') color = CON_TEXT_COLORS[6];
			if (ch=='7') color = CON_TEXT_COLORS[7];
			if (ch!='^') continue; // sequences like "^^ABC" should be transformed to "^ABC"
		}
		
		SetColor(color);
		DrawChar(x + xoffs, y, ch);
		xoffs++;
	}
	
	SetColor(old_color);
}


//
//	EWinConsole::DrawLines
//
void EWinConsole::DrawLines(void)
{
	SetColor(CON_TEXT_COLORS[7]);

	int ln    = scroll - 1;
	int scrln = SIZE_Y - 4;
	while (1) {
		if (ln<0) break;
		if (scrln<0) break;

		for (int j=0; j<SIZE_X; j++) {
			DrawChar(j, scrln, ' ');
		}		
		DrawStringClr(0, scrln, lines[ln].c_str());
		
		ln--;
		scrln--;
	}
}


//
//	EWinConsole::DrawCmdLine
//
void EWinConsole::DrawCmdLine(void)
{
	SetColor(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);

	DrawString(0, SIZE_Y-2, "]");
	DrawString(1, SIZE_Y-2, cmdline.cmdline.c_str());
	
	COORD cur_pos;
	cur_pos.X = cmdline.cursor + 1;
	cur_pos.Y = SIZE_Y-2;
	SetConsoleCursorPosition(houtput, cur_pos);
}


//
//	EWinConsole::DrawInfoLine
//
void EWinConsole::DrawInfoLine(void)
{
	uint clr = BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
	SetColor(clr);
	
	DrawString(   0, SIZE_Y-1, "Enter");
	DrawString(   6, SIZE_Y-1, "Tab  ");
	DrawString(  12, SIZE_Y-1, "PgUp ");
	DrawString(  18, SIZE_Y-1, "PgDn ");
	DrawString(  24, SIZE_Y-1, "Up   ");
	DrawString(  30, SIZE_Y-1, "Down ");
	
	for (uint i=36; i<SIZE_X; i++) {
		DrawChar(i, SIZE_Y-1, ' ');
	}
}

//
//	EWinConsole::UpdateBuffer
//
void EWinConsole::UpdateConsole(void)
{
	//
	//	Prepare buffer :
	//
	memset(buffer, 0, sizeof(buffer));
	/*buffer[0].Char.AsciiChar = 'A';							    
	buffer[0].Attributes = FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY;*/

	DrawLines();
	DrawInfoLine();
	DrawCmdLine();
	
	//
	//	Write buffer :
	//
	CONSOLE_SCREEN_BUFFER_INFO	info;
	GetConsoleScreenBufferInfo(houtput, &info);
	
	COORD size;
	size.X = SIZE_X;
	size.Y = SIZE_Y;	

	COORD point;
	point.X = info.srWindow.Left;
	point.Y = info.srWindow.Top;
	VERIFY( WriteConsoleOutput(houtput, buffer, size, point, &info.srWindow) );
}
